<template>
  <fs-page>
    <el-row class="menu-el-row">
      <el-col :span="6" style="height: 600px">
        <div class="menu-box menu-left-box" style="width: auto;overflow-x: auto;">
          <MenuTreeCom
              ref="menuTreeRef"
              :treeData="menuTreeData"
              @treeClick="handleTreeClick"
              style="width: auto;overflow-x: auto;"
          />
        </div>
      </el-col>

      <el-col :span="18">
        <el-row class="menu-box menu-right-box">
          <el-scrollbar>
            <el-col>
              <!--期刊ID--> <!--期刊名-->
              <el-row :gutter="15">
                <el-col :span="6">
                  <span class="font20 font-bold">期刊智能体ID：</span>
                  <span class="font20 font-bold" style="color: #0d84ff">{{ currentAgent.id }}</span>
                </el-col>
                <el-col :span="18">
                  <span class="font20 font-bold">期刊智能体名称：</span>
                  <span class="font20 font-bold" style="color: #0d84ff">{{ currentAgent.name }}</span>
                </el-col>
              </el-row>

              <div class="line" style="border-top: 2px solid var(--el-border-color)"/>
              <!--期刊爬取年份-->
              <el-row :gutter="15">
                <el-col :span="24">
                  <div class="mb15">
                    <el-descriptions
                        class="margin-top"
                        :column="1"
                        size="large"
                        border
                    >
                      <el-descriptions-item>
                        <template #label>
                          <div class="cell-item">
                            <el-icon size="20">
                              <calendar/>
                            </el-icon>
                            <span class="font20 font-bold">
                            &nbsp 期刊智能体任务年份
                          </span>
                          </div>
                        </template>
                        <span class="font20 font-bold" style="color: #0d84ff">
                        {{ logYears }}
                      </span>
                      </el-descriptions-item>

                      <el-descriptions-item>
                        <template #label>
                          <div class="cell-item">
                            <el-icon size="20">
                              <Timer/>
                            </el-icon>
                            <span class="font20 font-bold">
                            &nbsp 任务启动时间
                          </span>
                          </div>
                        </template>
                        <span class="font20 font-bold" style="color: #0d84ff">
                        {{ lastCrawlTime }}
                      </span>
                      </el-descriptions-item>
                    </el-descriptions>
                  </div>

                </el-col>
              </el-row>
              <div class="line" style="border-top: 2px solid var(--el-border-color)"/>
              <!--智能体工作状态-->

              <el-row :gutter="15">
                <el-col :span="24">
                  <el-row :gutter="15">
                    <el-col :span="24">
                      <span class="font20 font-bold">智能体工作状态：</span>
                      <span class="font20 font-bold" style="color: #67C23A"
                            v-if="currentAgent.status == 1">执行中</span>
                      <span class="font20 font-bold" style="color: #b1b3b8" v-else>空闲中</span>
                      <!--                    <el-button type="warning" style="margin-left: 15px">暂停任务</el-button>-->
                      <!--                    <el-button type="danger">终止爬取</el-button>-->
                    </el-col>
                  </el-row>
                  <!--数据统计-->
                  <el-row :gutter="15" v-if="currentAgent.status === 1">
                    <el-col :span="24" class="flex" style="flex-direction: column;">
                      <span class="font20 font-bold">数据统计：</span>
                      <div style="height: 300px; width: 100%">
                        <div style="height: 100%" ref="spiderLineRef"></div>
                      </div>
                    </el-col>
                  </el-row>
                  <!--已爬取文献-->
                  <el-row :gutter="15" v-if="currentAgent.status === 1">
                    <el-col :span="24" class="flex" style="flex-direction: column;">
                      <span class="font20 font-bold">已爬取文献：</span>
                      <div style="height: 350px; width: 100%">
                        <el-table
                            :data="paginatedData"
                            style="width: 100%; overflow: auto;"
                            stripe
                            :max-height="300"
                            :header-cell-style="{ backgroundColor: '#f5f7fa' }"
                            border
                            @row-click="handleRowClick">
                          <el-table-column label="文献标题" prop="article_title">
                          </el-table-column>
                        </el-table>

                        <!-- 弹窗展示文献信息 -->
                        <el-dialog
                            v-model="dialogVisible"
                            title="文献详细信息"
                            width="60%"
                            :before-close="handleClose">

                          <!-- 文献详细信息展示 -->
                          <el-row :gutter="20">
                            <el-col :span="12">
                              <el-card>
                                <div slot="header" class="clearfix">
                                  <span>文献标题</span>
                                </div>
                                <div class="text item-content">{{ currentArticle.article_title }}</div>
                              </el-card>
                            </el-col>

                            <el-col :span="12">
                              <el-card>
                                <div slot="header" class="clearfix">
                                  <span>作者</span>
                                </div>
                                <div class="text item-content">{{ currentArticle.authors }}</div>
                              </el-card>
                            </el-col>
                          </el-row>

                          <el-row :gutter="20" style="margin-top: 20px;">
                            <el-col :span="12">
                              <el-card>
                                <div slot="header" class="clearfix">
                                  <span>出版年份</span>
                                </div>
                                <div class="text item-content">{{ currentArticle.publication_year }}</div>
                              </el-card>
                            </el-col>

                            <el-col :span="12">
                              <el-card>
                                <div slot="header" class="clearfix">
                                  <span>DOI</span>
                                </div>
                                <div class="text item-content">{{ currentArticle.doi }}</div>
                              </el-card>
                            </el-col>
                          </el-row>

                          <el-row :gutter="20" style="margin-top: 20px;">
                            <el-col :span="12">
                              <el-card>
                                <div slot="header" class="clearfix">
                                  <span>文献来源</span>
                                </div>
                                <div class="text item-content">{{ currentArticle.source_title }}</div>
                              </el-card>
                            </el-col>

                            <el-col :span="12">
                              <el-card>
                                <div slot="header" class="clearfix">
                                  <span>被引次数</span>
                                </div>
                                <div class="text item-content">{{ currentArticle.times_cited_wos_core }}</div>
                              </el-card>
                            </el-col>
                          </el-row>

                          <el-row :gutter="20" style="margin-top: 20px;">
                            <el-col :span="12">
                              <el-card>
                                <div slot="header" class="clearfix">
                                  <span>语言</span>
                                </div>
                                <div class="text item-content">{{ currentArticle.language }}</div>
                              </el-card>
                            </el-col>

                            <el-col :span="12">
                              <el-card>
                                <div slot="header" class="clearfix">
                                  <span>期刊 ISSN</span>
                                </div>
                                <div class="text item-content">{{ currentArticle.ISSN }}</div>
                              </el-card>
                            </el-col>
                          </el-row>

                          <el-row style="margin-top: 20px;">
                            <el-col :span="24">
                              <el-card>
                                <div slot="header" class="clearfix">
                                  <span>摘要</span>
                                </div>
                                <div class="text item-content">{{ currentArticle.abstract }}</div>
                              </el-card>
                            </el-col>
                          </el-row>

                          <!-- 关闭按钮 -->
                          <span slot="footer" class="dialog-footer">
      <el-button @click="dialogVisible = false" type="primary">关闭</el-button>
    </span>
                        </el-dialog>

                        <!-- 分页组件 -->
                        <el-pagination
                            @current-change="handlePageChange"
                            :page-size="pageSize"
                            :current-page="currentPage"
                            :total="totalItems"
                            layout="total, prev, pager, next, jumper"
                        ></el-pagination>
                      </div>
                    </el-col>
                  </el-row>
                </el-col>
              </el-row>
              <div class="line" style="border-top: 2px solid var(--el-border-color)"/>
              <!--智能体工作日志-->
              <el-row :gutter="15">
                <!--                <el-col :span="12" class="flex" style="flex-direction: column">-->
                <!--                  <span class="font20 font-bold">爬取日志信息统计：</span>-->
                <!--                  <div style="height: 300px; width: 100%">-->
                <!--                    <div style="height: 100%" ref="logBarRef"></div>-->
                <!--                  </div>-->
                <!--                </el-col>-->
                <el-col :span="24" class="flex" style="flex-direction: column">
                  <div>
                    <span class="font20 font-bold">爬取日志详细信息：</span>
                    <span>
                    <el-select
                        v-model="currentAgent.currentLogYear"
                        placeholder="请选择日志年份"
                        size="large"
                        style="width: 240px"
                        @change="getLogInfo"
                    >
                    <el-option
                        v-for="year in logYears"
                        :key="year"
                        :label="year"
                        :value="year"
                    />
                    </el-select>
                  </span>
                    <span>
                      <el-table :data="logInfo" style="width: 100%" max-height="250">
                        <el-table-column fixed prop="status" label="状态" width="180"/>
                        <el-table-column fixed prop="create_time" label="时间"/>
                        <el-table-column prop="info" label="内容"/>
                      </el-table>
                  </span>
                  </div>
                  <!--                <el-table :data="" style="width: 100%">-->
                  <!--                  <el-table-column label="Date" width="180">-->
                  <!--                    <template #default="scope">-->
                  <!--                      <div style="display: flex; align-items: center">-->
                  <!--                        <el-icon><timer /></el-icon>-->
                  <!--                        <span style="margin-left: 10px">{{ scope.row.date }}</span>-->
                  <!--                      </div>-->
                  <!--                    </template>-->
                  <!--                  </el-table-column>-->
                  <!--                  <el-table-column label="Name" width="180">-->
                  <!--                    <template #default="scope">-->
                  <!--                      <el-popover effect="light" trigger="hover" placement="top" width="auto">-->
                  <!--                        <template #default>-->
                  <!--                          <div>name: {{ scope.row.name }}</div>-->
                  <!--                          <div>address: {{ scope.row.address }}</div>-->
                  <!--                        </template>-->
                  <!--                        <template #reference>-->
                  <!--                          <el-tag>{{ scope.row.name }}</el-tag>-->
                  <!--                        </template>-->
                  <!--                      </el-popover>-->
                  <!--                    </template>-->
                  <!--                  </el-table-column>-->
                  <!--                  <el-table-column label="Operations">-->
                  <!--                    <template #default="scope">-->
                  <!--                      <el-button size="small" @click="handleEdit(scope.$index, scope.row)">-->
                  <!--                        Edit-->
                  <!--                      </el-button>-->
                  <!--                      <el-button-->
                  <!--                          size="small"-->
                  <!--                          type="danger"-->
                  <!--                          @click="handleDelete(scope.$index, scope.row)"-->
                  <!--                      >-->
                  <!--                        Delete-->
                  <!--                      </el-button>-->
                  <!--                    </template>-->
                  <!--                  </el-table-column>-->
                  <!--                </el-table>-->
                </el-col>
              </el-row>
            </el-col>
          </el-scrollbar>
        </el-row>
      </el-col>
    </el-row>
  </fs-page>
</template>

<script lang="ts" setup name="single">
import {ref, onMounted, nextTick, onActivated, watch, reactive, computed} from 'vue';
import XEUtils from 'xe-utils';
import MenuTreeCom from './components/MenuTreeCom/index.vue';
import * as api from './api';
import {AgenetTreeItem, APIResponseData, MenuTreeItemType} from './types';
import * as echarts from "echarts";
import {storeToRefs} from 'pinia';
import {useThemeConfig} from '/@/stores/themeConfig';
import {useTagsViewRoutes} from '/@/stores/tagsViewRoutes';
import {flattedChildren} from 'element-plus/es/utils';
import {Calendar, Timer} from "@element-plus/icons-vue";
import {response} from "/@/utils/tools";
import {getStatistics} from "./api";

const storesTagsViewRoutes = useTagsViewRoutes();
const storesThemeConfig = useThemeConfig();
const {themeConfig} = storeToRefs(storesThemeConfig);
const {isTagsViewCurrenFull} = storeToRefs(storesTagsViewRoutes);


let menuTreeData = ref();
let menuTreeCacheData = ref<MenuTreeItemType[]>([]);
let drawerVisible = ref(false);
let drawerFormData = ref<Partial<MenuTreeItemType>>({});
let menuTreeRef = ref<InstanceType<typeof MenuTreeCom> | null>(null);

const currentYear: number = new Date().getFullYear();
const allYears: number[] = []
for (let i = 0; i < 20; i++) {
  allYears.push(currentYear - i);
}

// let years = ref(allYears);// 年份（最近10年）
// let checkedYears = ref([2023, 2021]);

const currentAgent = ref();
currentAgent.value = {
  id: '',
  name: "请选择智能体",
  status: 0,
  isLeaf: true,
  currentLogYear: '',
}

const logYears = ref();
const logInfo = ref();
const lastCrawlTime = ref();

const getData = async () => {
  // 更新树形结构 (界面上渲染的数据)
  menuTreeData.value = [
    {
      id: 'runningGroup',
      name: '运行智能体',
      children: [],
    },
    {
      id: 'idleGroup',
      name: '空闲智能体',
      children: [],
    },
  ];
}

/**
 * 菜单的点击事件
 */
const handleTreeClick = (record: AgenetTreeItem) => {
  logYears.value = null;
  lastCrawlTime.value = null;
  currentAgent.value = record;
  const params: any = {
    id: record.id
  }
  api.getStatistics(params).then((response: any) => {
    let data = response.data;
    // 提取年份列表、实际数量、预期数量和消耗时间
    years = Object.keys(data).filter(year => data[year].expectNum > 0);
    logYears.value = years
  });
  api.getRecord(params).then((response: any) => {
    const records = response.data
    // console.log(records[records.length - 1])
    lastCrawlTime.value = new Date((records[records.length - 1].last_crawl_time + 8 * 3600) * 1000)
        .toISOString()
        .replace('T', ' ')
        .substring(0, 19);

  })
  params.year = 2022;
  params.pageSize = 20033;
  api.getDocuments(params).then((response: any) => {
    const data = response.data;
    totalItems.value = data.length;
  });
  params.pageNum = currentPage.value;
  params.pageSize = pageSize.value;

  api.getDocuments(params).then((response: any) => {
    const data = response.data;
    paginatedData.value = data;
    // console.log(paginatedData.value)
  });
};

const handleDrawerClose = (type?: string) => {
  if (type === 'submit') {
    getData();
  }
  drawerVisible.value = false;
  drawerFormData.value = {};
};

const getLogInfo = async () => {
  const res = await api.getCrawlLog(currentAgent.value.id);
  const data = res.data;
  logInfo.value = data.crawl_log[currentAgent.value.currentLogYear].map(item => ({
    status: item.status,
    create_time: new Date((item.create_time + 8 * 3600) * 1000).toLocaleString(), // 加8小时并转换为可读时间
    info: item.info
  }));
}

let currentArticle = ref();
let dialogVisible = ref(false);

// 行点击事件处理函数
const handleRowClick = (row) => {
  const publicationYear = Number(row.publication_year);  // 使用 Number 转换
  row.publication_year = isNaN(publicationYear) ? 0 : publicationYear;  // 处理无效数字（例如空值或非数字字符）
  currentArticle = row;
  dialogVisible.value = true;  // 显示弹窗
}

onMounted(() => {
  getData();
});

let global: any = {
  progressPieChart: null,
  speedGaugeChart: null,
  logBarChart: null,
  dispose: [null, '', undefined]
};

const spiderLineRef = ref();
const speedGaugeRef = ref();
const logBarRef = ref();

const state = reactive({
  myCharts: [],
  charts: {
    theme: '',
    bgColor: '',
    color: '#303133',
  }
})

const currentPage = ref(1); // 当前页
const pageSize = ref(20); // 每页显示的数量
const totalItems = ref(20033); // 总条目数
let paginatedData = ref([]);

//页数变化时
const handlePageChange = (page: number) => {
  currentPage.value = page;
  // console.log(currentPage.value);
  const params = {
    id: currentAgent.value.id,
    year: 2022,
    pageNum: currentPage.value,
    pageSize: pageSize.value
  }
  api.getDocuments(params).then((response: any) => {
    const data = response.data;
    paginatedData.value = data;
  });
}


let years = [];
let realNum = [];
let expectNum = [];
let costTime = [];
const initSpiderData = async () => {
  return new Promise((resolve, reject) => {
    const params = {
      id: currentAgent.value.id
    }
    api.getStatistics(params).then((res: any) => {
      let data = res.data;
      // 提取年份列表、实际数量、预期数量和消耗时间
      years = Object.keys(data).filter(year => data[year].expectNum > 0);

      // 根据过滤后的 years 重新提取对应数据
      realNum = years.map(year => data[year].realNum);       // 对应预期数量 > 0 的实际数量
      expectNum = years.map(year => data[year].expectNum);   // 只包含 > 0 的预期数量
      costTime = years.map(year => data[year].costTime);     // 对应预期数量 > 0 的消耗时间
      resolve();
    }).catch((error) => {
      console.error('API 请求失败:', error);
      reject(error);  // 如果请求失败，调用 reject
    })
  })
}

// 初始化爬取数据统计
const initSpiderLineChart = async () => {
  if (currentAgent.value.id) await initSpiderData();
  if (!global.dispose.some((b: any) => b === global.progressPieChart)) global.progressPieChart.dispose();
  global.progressPieChart = <any>echarts.init(spiderLineRef.value, state.charts.theme);
  const option = {
    tooltip: {
      trigger: 'axis'
    },
    legend: {
      data: ['实际数量', '预期数量', '消耗时间']
    },
    grid: {
      left: '3%',
      right: '4%',
      bottom: '3%',
      containLabel: true
    },
    xAxis: [
      {
        type: 'category',
        data: years,
        axisTick: {
          alignWithLabel: true
        }
      }
    ],
    yAxis: [
      {
        type: 'value',
        name: '爬取文献数量',
        position: 'left',
        axisLine: {
          lineStyle: {
            color: '#33cc33'
          }
        },
        axisLabel: {
          formatter: '{value}'
        }
      },
      {
        type: 'value',
        name: '消耗时间 (秒)',
        position: 'right',
        axisLine: {
          lineStyle: {
            color: '#ff5733'
          }
        },
        axisLabel: {
          formatter: '{value} s'
        }
      }
    ],
    series: [
      {
        name: '实际数量',
        type: 'bar',
        data: realNum,  // 实际数量数据
        barWidth: '30%',
        itemStyle: {
          color: '#4caf50'
        }
      },
      {
        name: '预期数量',
        type: 'bar',
        data: expectNum,  // 预期数量数据
        barWidth: '30%',
        itemStyle: {
          color: '#ff9800'
        }
      },
      {
        name: '消耗时间',
        type: 'line',
        yAxisIndex: 1,
        data: costTime,  // 消耗时间数据
        smooth: true,
        lineStyle: {
          color: '#ff5733'
        },
        symbol: 'circle',
        symbolSize: 8
      }
    ]
  };

  (<any>global.progressPieChart).setOption(option);
  (<any>state.myCharts).push(global.progressPieChart);
};

// 初始化爬取速度gauge图
const initSpeedGaugeChart = () => {
  if (!global.dispose.some((b: any) => b === global.speedGaugeChart)) global.speedGaugeChart.dispose();
  global.speedGaugeChart = <any>echarts.init(speedGaugeRef.value, state.charts.theme);
  const option = {
    tooltip: {
      formatter: '<b>{a}</b> <br/>{b}'
    },
    series: [
      {
        name: '爬取速度',
        type: 'gauge',
        progress: {
          show: true
        },
        detail: {
          valueAnimation: true,
          formatter: '{value}'
        },
        data: [
          {
            value: 0,
            name: '条/分'
          }
        ]
      }
    ]
  };

  (<any>global.speedGaugeChart).setOption(option);
  (<any>state.myCharts).push(global.speedGaugeChart);
};

const initLogBarChart = () => {
  if (!global.dispose.some((b: any) => b === global.logBarChart)) global.logBarChart.dispose();
  global.logBarChart = <any>echarts.init(logBarRef.value, state.charts.theme);
  const option = {
    xAxis: {
      type: 'category',
      data: ['Fatal', 'Error', 'Warn', 'Info', 'Debug']
    },
    yAxis: {
      type: 'value'
    },
    series: [
      {
        data: [
          {
            value: 0,
            itemStyle: {
              color: '#c45656'
            }
          },
          {
            value: 0,
            itemStyle: {
              color: ' #fab6b6'
            }
          },
          {
            value: 0,
            itemStyle: {
              color: ' #b88230'
            }
          },
          {
            value: 0,
            itemStyle: {
              color: '#529b2e'
            }
          },
          {
            value: 0,
            itemStyle: {
              color: '#73767a'
            }
          }
        ],
        type: 'bar'
      }
    ]
  };

  (<any>global.logBarChart).setOption(option);
  (<any>state.myCharts).push(global.logBarChart);
}

// 批量设置 echarts resize
const initEchartsResizeFun = () => {
  nextTick(() => {
    for (let i = 0; i < state.myCharts.length; i++) {
      setTimeout(() => {
        (<any>state.myCharts[i]).resize();
      }, i * 1000);
    }
  });
};
// 批量设置 echarts resize
const initEchartsResize = () => {
  window.addEventListener('resize', initEchartsResizeFun);
};
// 页面加载时
onMounted(() => {
  initEchartsResize();
});
// 由于页面缓存原因，keep-alive
onActivated(() => {
  initEchartsResizeFun();
});

// 监听 vuex 中的 tagsview 开启全屏变化，重新 resize 图表，防止不出现/大小不变等
watch(
    () => isTagsViewCurrenFull.value,
    () => {
      initEchartsResizeFun();
    }
);

// 监听 vuex 中是否开启深色主题
watch(
    () => themeConfig.value.isIsDark,
    (isIsDark) => {
      nextTick(() => {
        state.charts.theme = isIsDark ? 'dark' : '';
        state.charts.bgColor = isIsDark ? 'transparent' : '';
        state.charts.color = isIsDark ? '#dadada' : '#303133';
        setTimeout(() => {
          initSpiderLineChart();
        }, 500);
        setTimeout(() => {
          initSpeedGaugeChart();
        }, 700);
        setTimeout(() => {
          initLogBarChart();
        }, 1000);
      });
    },
    {
      deep: true,
      immediate: true,
    }
);

watch(
    () => currentAgent.value.status,
    (newValue) => {
      if (newValue === 1) {
        // 如果 currentAgent.status 变为 1，则开始初始化图表
        nextTick(() => {
          setTimeout(() => {
            initSpiderLineChart();
          }, 500);
          setTimeout(() => {
            initSpeedGaugeChart();
          }, 700);
          setTimeout(() => {
            initLogBarChart();
          }, 1000);
        })
      } else {
        nextTick(() => {
          for (let i = 0; i < state.myCharts.length; i++) {
            setTimeout(() => {
              (<any>state.myCharts[i]).dispose();
            }, i * 1000);
          }
        })
      }
    },
    {
      immediate: true, // 监听器立即开始工作
    }
);

</script>

<style lang="scss" scoped>
.menu-el-row {
  height: 100%;
  overflow: hidden;

  .el-col {
    height: 100%;
    padding: 10px 0;
    box-sizing: border-box;
  }
}

.menu-box {
  height: 100%;
  padding: 10px;
  background-color: #fff;
  box-sizing: border-box;
}

.menu-left-box {
  position: relative;
  border-radius: 0 8px 8px 0;
  margin-right: 10px;
}

.menu-right-box {
  border-radius: 8px 0 0 8px;
}

.el-descriptions {
  margin-top: 20px;
}

.cell-item {
  display: flex;
  align-items: center;
}

//对话框风格
.item-content {
  font-size: 14px;
  color: #606266;
  padding: 10px 0;
}

.el-card {
  border-radius: 8px;
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
}

.el-row {
  margin-top: 20px;
}

.el-button {
  background-color: #409eff;
  border-color: #409eff;
  color: white;
  font-weight: bold;
}

.el-button:hover {
  background-color: #66b1ff;
}

.dialog-footer {
  text-align: center;
  padding: 10px;
}

.el-card .clearfix {
  font-size: 16px;
  font-weight: 600;
  color: #409eff;
}

//分页器风格
.el-pagination {
  justify-content: center;
  padding: 10px;
}

</style>
